# coding: utf-8
# author: t_wolf

from commons import *


class DbUtil:
    def __init__(self):
        pass

    class DbType:
        def __init__(self):
            pass

        MYSQL = 'mysql'
        # ORACLE = 'ORACLE'

    @staticmethod
    def auto_connect(**kwargs):
        def wrapper(cls):
            db_conn = None
            if kwargs['db_type'] == DbUtil.DbType.MYSQL:
                db_conn = web.database(
                    dbn=kwargs['db_type'], host=kwargs['host'], port=kwargs['port'],
                    user=kwargs['user'], pw=kwargs['pw'], db=kwargs['db']
                )
            setattr(cls, "db", db_conn)
            return cls

        return wrapper

    @staticmethod
    def roll_back_on_exception(db_conn):
        def wrap_func(func):
            def wrapper(*args, **kwargs):
                trans = db_conn.transaction()
                try:
                    res = func(*args, **kwargs)
                except Exception:
                    trans.rollback()
                    raise
                else:
                    trans.commit()
                return res

            return wrapper

        return wrap_func


@DbUtil.auto_connect(db_type=DbUtil.DbType.MYSQL, host=CONFIGS.DB.host, port=CONFIGS.DB.port,
                     user=CONFIGS.DB.username, pw=CONFIGS.DB.password, db=CONFIGS.DB.database)
class DB:
    INSERT = 0
    DELETE = 1
    UPDATE = 2
    QUERY = 4

    db = None

    def __init__(self):
        pass
